<template>
	<view class="page">

		<view class="avatar">
			<u--image :src="model1.userInfo.headimgurl" width="110px" height="110px" shape="circle"></u--image>
		</view>
		<view class="avatar-btn">
			<u-button @tap="upload" text="更改头像"></u-button>
		</view>
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form labelPosition="left" :model="model1" :rules="rules" ref="uForm">
			<u-form-item label="姓名" prop="userInfo.nickname" :required="true" borderBottom ref="item1">
				<u--input v-model="model1.userInfo.nickname" border="none" placeholder="请输入姓名" maxlength="8"></u--input>
			</u-form-item>
			<u-form-item label="手机" prop="userInfo.phone" :required="true" borderBottom ref="item1">
				<u--input v-model="model1.userInfo.phone" disabled border="none"></u--input>
				<u-button slot="right" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" text="获取手机号码" :disabled="model1.userInfo.phone !=''" 
					type="success" size="mini"></u-button>
			</u-form-item>
			<u-form-item label="性别" prop="userInfo.sex" borderBottom @click="showSex = true;" ref="item1">
				<u--input v-model="model1.userInfo.sex" disabled disabledColor="#ffffff" placeholder="请选择性别"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>

			<u-form-item label="生日" prop="userInfo.birthday" borderBottom @click="showBirthday = true;" ref="item1">
				<u--input v-model="model1.userInfo.birthday" disabled disabledColor="#ffffff" placeholder="请选择生日"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>

			<u-form-item label="兴趣" prop="tagList" borderBottom ref="item1">
				<u-checkbox-group v-model="model1.tagList" shape="square" @change="change">
					<view style="display: flex;flex-wrap: wrap;">
						<u-checkbox :customStyle="{margin: '5px'}" v-for="(item, index) in checkTagList" :key="index"
							:label="item.name" :name="item.name" :checked="item.checked">
						</u-checkbox>
					</view>
				</u-checkbox-group>
			</u-form-item>

			<u-form-item label="擅长类型" borderBottom ref="item1" v-if="model1.userInfo.leader == '是'">
				<u-checkbox-group v-model="model1.leaderTagList" shape="square" @change="change">
					<view style="display: flex;flex-wrap: wrap;">
						<u-checkbox :customStyle="{margin: '5px'}" v-for="(item, index) in checkLeaderTagList"
							:key="index" :label="item.name" :name="item.name" :checked="item.checked">
						</u-checkbox>
					</view>
				</u-checkbox-group>
			</u-form-item>

			<u-form-item label="简介" borderBottom ref="item1">
				<u--textarea v-model="model1.userInfo.introduction" placeholder="请输入内容" count
					maxlength="180"></u--textarea>
			</u-form-item>

		</u--form>

		<u-button @click="submit" customStyle="background-color: #ffd91d">提交</u-button>
		<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false" @select="sexSelect">
		</u-action-sheet>

 
		
		<u-datetime-picker :minDate="-1786778555000" :maxDate="birthday" :show="showBirthday" :value="birthday"
			mode="date" closeOnClickOverlay @confirm="birthdayConfirm" @cancel="birthdayClose"
			@close="birthdayClose"></u-datetime-picker>
	</view>
</template>

<script>
	import * as UserApi from '@/api/user'
	import * as Config from '@/utils/config.js'
	import * as EventApi from '@/api/event.js';
	export default {
		data() {
			return {
				showSex: false,
				showBirthday: false,
				model1: {
					userInfo: {
						headimgurl: '',
						nickname: '',
						sex: '',
						phone: '',
						introduction: ''
					},
					tagList: [],
					leaderTagList: [],
				},
				actions: [{
						name: '男',
					},
					{
						name: '女',
					},
				],
				rules: {
					'userInfo.nickname': {
						type: 'string',
						required: true,
						max: 30,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'userInfo.phone': {
						type: 'number',
						required: true,
						max: 11,
						min: 11,
						message: '请填写正确手机号码',
						trigger: ['blur', 'change']
					},
					// 'userInfo.sex': {
					// 	type: 'string',
					// 	max: 1,
					// 	required: true,
					// 	message: '请选择男或女',
					// 	trigger: ['blur', 'change']
					// },
					// 'userInfo.birthday': {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请选择生日',
					// 	trigger: ['change']
					// },
					// tagList: {
					// 	type: 'array',
					// 	min: 1,
					// 	required: true,
					// 	message: '不能太宅，至少选一项',
					// 	trigger: ['change']
					// },
				},
				radio: '',
				switchVal: false,
				checkTagList: [],
				checkLeaderTagList: [],
				birthday: Number(new Date())
			}
		},
		onLoad() {

		},
		onShow() {
			// 获取当前用户信息
			this.checkTagList = []
			this.checkLeaderTagList = []
			this.getUserInfo()

		},
		methods: {
			
			open() {
			  // console.log('open');
			},
			close() {
			  this.group_tag_show = false
			  // console.log('close');
			},
					
					
					
			getPhone() {
				if (this.model1.userInfo.phone == '') {
					uni.navigateTo({
						url: "/pages/login/index"
					})
				}

			},
			checkboxClick(index) {
				let s = this.model1.userInfo.tag[index].select
				this.model1.userInfo.tag[index].select = s == 0 ? 0 : 1
			},
			sexSelect(e) {
				this.model1.userInfo.sex = e.name
				this.$refs.uForm.validateField('userInfo.sex')
			},
			// 获取当前用户信息
			getUserInfo() {
				UserApi.userInfo().then(res => {
					this.model1.userInfo = res.info
					this.getTags()
				})
			},
			birthdayClose() {
				this.showBirthday = false
				this.$refs.uForm.validateField('userInfo.birthday')
			},
			birthdayConfirm(e) {
				this.showBirthday = false
				this.model1.userInfo.birthday = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				this.$refs.uForm.validateField('userInfo.birthday')
			},

			change(e) {
				// console.log(e);
			},
			getTags() {
				EventApi.tags().then(res => {
					let list = res.info.tag.split(',')

					list.forEach(e => {
						let tagB = this.model1.userInfo.tag ? this.model1.userInfo.tag.includes(e) : false
						this.checkTagList.push({
							name: e,
							checked: tagB
						})
						if (tagB) {
							this.model1.tagList.push(e)
						}

						let leaderB = this.model1.userInfo.leader_tag ? this.model1.userInfo.leader_tag
							.includes(e) : false
						this.checkLeaderTagList.push({
							name: e,
							checked: leaderB
						})
						if (leaderB) {
							this.model1.leaderTagList.push(e)
						}
					})


				})
			},
			
			getPhoneNumber(e) {
				var self = this;
				if (e.detail.errMsg !== 'getPhoneNumber:ok') {
					return false;
				}
				uni.showLoading({
					title: "正在处理",
					mask: true
				});
			
				UserApi.bindMobile({
					code: e.detail.code
				}).then(res => {
					uni.hideLoading();
					if (res.status == 200) {
						this.model1.userInfo.phone = res.phone;
					}
			
				})
			
			},
			
			submit() {
				if (this.model1.userInfo.headimgurl == '') {
					uni.$u.toast('请上传头像')
					return false
				}
				this.$refs.uForm.validate().then(res => {

					let tag = "";
					this.model1.tagList.forEach(e => {
						tag += e + ','
					})
					let leader_tag = "";
					this.model1.leaderTagList.forEach(e => {
						leader_tag += e + ','
					})

					this.model1.userInfo.tag = tag.substr(0, tag.length - 1)
					this.model1.userInfo.leader_tag = leader_tag.substr(0, leader_tag.length - 1)

					UserApi.userUpdate(this.model1.userInfo).then(res => {
						uni.$u.toast(res.info)

						if (uni.getStorageSync('share_order_param')) {
							uni.navigateTo({
								url: '/pages/activity/detail?id=' + uni.getStorageSync(
									'share_order_param').id
							});

						} else {
							let currentPagesList = getCurrentPages()
							if (currentPagesList.length <= 1) {
								uni.reLaunch({
									url: '/pages/user/user'
								})
							} else {
								uni.navigateBack();
							}
						}

					})
				}).catch(errors => {
					//	uni.$u.toast('校验失败')
				})
			},

			upload() {
				let that = this;
				uni.chooseImage({
					success: (chooseImageRes) => {
						that.model1.userInfo.headimgurl = chooseImageRes.tempFilePaths[0];
						uni.uploadFile({
							header: {
								Authorization: Config.getStorageUserId(),
							},
							url: Config.baseUrl +
								'/api/miniapp/user.php?act=upload_img',
							filePath: chooseImageRes.tempFilePaths[0],
							name: 'file',
							success: (uploadFileRes) => {
								//uni.$u.toast(res.info)
								let d = JSON.parse(uploadFileRes.data)
								if (d.status == 200) {
									this.model1.userInfo.headimgurl = d.url
									uni.$u.toast(d.info)
								} else {
									uni.$u.toast('更新失败')
								}

							}
						});
					}
				});
			},

		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	}
</script>

<style scoped lang="scss">
	
	@import url("asset/style.css");
	.page {
		margin: 30rpx;

		.avatar {
			height: 250rpx;
			text-align: center;
			width: 200rpx;
			margin: auto;
		}

		.avatar-btn {
			width: 200rpx;
			margin: auto;
		}

		.tag {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			margin-top: 20rpx;

			.tag-item {
				margin-bottom: 20rpx;
			}
		}

		.submit {
			background-color: #ffd91d;
		}
	}
</style>